package jnpf.fico.service.impl;

import cn.hutool.core.collection.IterUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.fico.entity.ZcglCwInvoiceEntity;
import jnpf.fico.entity.ZcglCwInvoiceItemEntity;
import jnpf.fico.entity.ZcglCwInvoicingEntity;
import jnpf.fico.mapper.ZcglCwInvoiceItemMapper;
import jnpf.fico.mapper.ZcglCwInvoiceMapper;
import jnpf.fico.mapper.ZcglCwInvoicingMapper;
import jnpf.fico.model.invoice.*;
import jnpf.fico.service.ZcglCwInvoiceService;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *
 * ZcglCwInvoice
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2024-10-30
 */
@Service
public class ZcglCwInvoiceServiceImpl extends ServiceImpl<ZcglCwInvoiceMapper, ZcglCwInvoiceEntity> implements ZcglCwInvoiceService {


        @Autowired
        private GeneraterSwapUtil generaterSwapUtil;

        @Autowired
        private UserProvider userProvider;

        @Autowired
        private AuthorizeService authorizeService;

        @Autowired
        private ZcglCwInvoiceItemMapper zcglCwInvoiceItemMapper;
        @Autowired
        private ZcglCwInvoicingMapper zcglCwInvoicingMapper;





    @Override
    public List<ZcglCwInvoiceEntity> getList(ZcglCwInvoicePagination zcglCwInvoicePagination){
        return getTypeList(zcglCwInvoicePagination,zcglCwInvoicePagination.getDataType());
    }
    @Override
    public List<ZcglCwInvoiceEntity> getTypeList(ZcglCwInvoicePagination zcglCwInvoicePagination,String dataType){
//        String userId=userProvider.get().getUserId();
//        List<String> AllIdList =new ArrayList();
//		List<List<String>> intersectionList =new ArrayList<>();
//		int total=0;
//		int zcglCwInvoiceNum =0;
//        QueryWrapper<ZcglCwInvoiceEntity> zcglCwInvoiceQueryWrapper=new QueryWrapper<>();
//		int zcglCwInvoiceItemNum =0;
//        QueryWrapper<ZcglCwInvoiceItemEntity> zcglCwInvoiceItemQueryWrapper=new QueryWrapper<>();
//		int zcglCwInvoicingNum =0;
//        QueryWrapper<ZcglCwInvoicingEntity> zcglCwInvoicingQueryWrapper=new QueryWrapper<>();
//            long zcglCwInvoiceItemcount = zcglCwInvoiceItemService.count();
//            long zcglCwInvoicingcount = zcglCwInvoicingService.count();
//		List<String> allSuperIDlist = new ArrayList<>();
//		String superOp ="";
//	if (ObjectUtil.isNotEmpty(zcglCwInvoicePagination.getSuperQueryJson())){
//		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcglCwInvoicePagination.getSuperQueryJson(), SuperQueryJsonModel.class);
//		String matchLogic = superQueryJsonModel.getMatchLogic();
//		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
//		for (ConditionJsonModel conditionjson : superQueryList){
//            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
//            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
//            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
//		    if (map.get("multiple") != null) {
//		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
//		            conditionjson.setFieldValue("[]");
//		        }
//		    }
//            conditionjson.setTableName(tableName);
//		}
//		List<String> allSuperList = new ArrayList<>();
//		List<List<String>> intersectionSuperList  = new ArrayList<>();
//        int zcglCwInvoiceNum1 = 0;
//        QueryWrapper<ZcglCwInvoiceEntity> zcglCwInvoiceSuperWrapper = new QueryWrapper<>();
//        zcglCwInvoiceNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglCwInvoiceSuperWrapper,superQueryList,matchLogic,"zcglCwInvoice")
//        ,new ZcglCwInvoiceEntity(),zcglCwInvoiceNum1);
//            if (zcglCwInvoiceNum1>0){
//            List<String> zcglCwInvoiceList =this.list(zcglCwInvoiceSuperWrapper).stream().map(ZcglCwInvoiceEntity::getId).collect(Collectors.toList());
//            allSuperList.addAll(zcglCwInvoiceList);
//            intersectionSuperList.add(zcglCwInvoiceList);
//            }
//        int zcglCwInvoiceItemNum1 = 0;
//        QueryWrapper<ZcglCwInvoiceItemEntity> zcglCwInvoiceItemSuperWrapper = new QueryWrapper<>();
//        zcglCwInvoiceItemNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglCwInvoiceItemSuperWrapper,superQueryList,matchLogic,"zcglCwInvoiceItem")
//        ,new ZcglCwInvoiceItemEntity(),zcglCwInvoiceItemNum1);
//            if (zcglCwInvoiceItemNum1>0 && zcglCwInvoiceItemcount>0){
//            List<String> zcglCwInvoiceItemList =zcglCwInvoiceItemService.list(zcglCwInvoiceItemSuperWrapper).stream().map(ZcglCwInvoiceItemEntity::getParentid).collect(Collectors.toList());
//            allSuperList.addAll(zcglCwInvoiceItemList);
//            intersectionSuperList.add(zcglCwInvoiceItemList);
//            }
//        int zcglCwInvoicingNum1 = 0;
//        QueryWrapper<ZcglCwInvoicingEntity> zcglCwInvoicingSuperWrapper = new QueryWrapper<>();
//        zcglCwInvoicingNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglCwInvoicingSuperWrapper,superQueryList,matchLogic,"zcglCwInvoicing")
//        ,new ZcglCwInvoicingEntity(),zcglCwInvoicingNum1);
//            if (zcglCwInvoicingNum1>0 && zcglCwInvoicingcount>0){
//            List<String> zcglCwInvoicingList =zcglCwInvoicingService.list(zcglCwInvoicingSuperWrapper).stream().map(ZcglCwInvoicingEntity::getParentid).collect(Collectors.toList());
//            allSuperList.addAll(zcglCwInvoicingList);
//            intersectionSuperList.add(zcglCwInvoicingList);
//            }
//		superOp = matchLogic;
//		//and or
//		if(matchLogic.equalsIgnoreCase("and")){
//		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
//		}else{
//		    allSuperIDlist = allSuperList;
//		}
//    }
//    boolean pcPermission = false;
//    boolean appPermission = false;
//    boolean	isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
//    if(isPc && pcPermission){
//		if (!userProvider.get().getIsAdministrator()){
//				Object zcglCwInvoiceObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCwInvoiceQueryWrapper,zcglCwInvoicePagination.getMenuId(),"zcgl_cw_invoice"));
//            if (ObjectUtil.isEmpty(zcglCwInvoiceObj)){
//                return new ArrayList<>();
//            } else {
//                zcglCwInvoiceQueryWrapper = (QueryWrapper<ZcglCwInvoiceEntity>)zcglCwInvoiceObj;
//                zcglCwInvoiceNum++;
//            }
//				Object zcglCwInvoiceItemObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCwInvoiceItemQueryWrapper,zcglCwInvoicePagination.getMenuId(),"zcgl_cw_invoice_item"));
//            if (ObjectUtil.isEmpty(zcglCwInvoiceItemObj)){
//                return new ArrayList<>();
//            } else {
//                zcglCwInvoiceItemQueryWrapper = (QueryWrapper<ZcglCwInvoiceItemEntity>)zcglCwInvoiceItemObj;
//                zcglCwInvoiceItemNum++;
//            }
//				Object zcglCwInvoicingObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCwInvoicingQueryWrapper,zcglCwInvoicePagination.getMenuId(),"zcgl_cw_Invoicing"));
//            if (ObjectUtil.isEmpty(zcglCwInvoicingObj)){
//                return new ArrayList<>();
//            } else {
//                zcglCwInvoicingQueryWrapper = (QueryWrapper<ZcglCwInvoicingEntity>)zcglCwInvoicingObj;
//                zcglCwInvoicingNum++;
//            }
//        }
//    }
//    if(!isPc && appPermission){
//		if (!userProvider.get().getIsAdministrator()){
//			Object zcglCwInvoiceObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCwInvoiceQueryWrapper,zcglCwInvoicePagination.getMenuId(),"zcglCwInvoice"));
//            if (ObjectUtil.isEmpty(zcglCwInvoiceObj)){
//                return new ArrayList<>();
//            } else {
//            zcglCwInvoiceQueryWrapper = (QueryWrapper<ZcglCwInvoiceEntity>)zcglCwInvoiceObj;
//            zcglCwInvoiceNum++;
//			}
//
//
//			Object zcglCwInvoiceItemObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCwInvoiceItemQueryWrapper,zcglCwInvoicePagination.getMenuId(),"zcglCwInvoiceItem"));
//            if (ObjectUtil.isEmpty(zcglCwInvoiceItemObj)){
//                return new ArrayList<>();
//            } else {
//            zcglCwInvoiceItemQueryWrapper = (QueryWrapper<ZcglCwInvoiceItemEntity>)zcglCwInvoiceItemObj;
//            zcglCwInvoiceItemNum++;
//			}
//
//
//			Object zcglCwInvoicingObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCwInvoicingQueryWrapper,zcglCwInvoicePagination.getMenuId(),"zcglCwInvoicing"));
//            if (ObjectUtil.isEmpty(zcglCwInvoicingObj)){
//                return new ArrayList<>();
//            } else {
//            zcglCwInvoicingQueryWrapper = (QueryWrapper<ZcglCwInvoicingEntity>)zcglCwInvoicingObj;
//            zcglCwInvoicingNum++;
//			}
//
//
//		}
//    }
//        if(isPc){
//			if(ObjectUtil.isNotEmpty(zcglCwInvoicePagination.getFullName())){
//            zcglCwInvoiceNum++;
//            zcglCwInvoiceQueryWrapper.lambda().like(ZcglCwInvoiceEntity::getFullName,zcglCwInvoicePagination.getFullName());
//                    }
//
//			if(ObjectUtil.isNotEmpty(zcglCwInvoicePagination.getStatus())){
//            zcglCwInvoiceNum++;
//                zcglCwInvoiceQueryWrapper.lambda().eq(ZcglCwInvoiceEntity::getStatus,zcglCwInvoicePagination.getStatus());
//                    }
//
//        }
//            if(zcglCwInvoiceItemNum>0){
//            List<String> zcglCwInvoiceItemIdList = zcglCwInvoiceItemService.list(zcglCwInvoiceItemQueryWrapper).stream().filter(t->StringUtil.isNotEmpty(t.getParentid())).map(t->t.getParentid()).collect(Collectors.toList());
//			long count = zcglCwInvoiceItemService.count();
//            if (count>0){
//				intersectionList.add(zcglCwInvoiceItemIdList);
//            }
//            AllIdList.addAll(zcglCwInvoiceItemIdList);
//            }
//            total+=zcglCwInvoiceItemNum;
//            if(zcglCwInvoicingNum>0){
//            List<String> zcglCwInvoicingIdList = zcglCwInvoicingService.list(zcglCwInvoicingQueryWrapper).stream().filter(t->StringUtil.isNotEmpty(t.getParentid())).map(t->t.getParentid()).collect(Collectors.toList());
//			long count = zcglCwInvoicingService.count();
//            if (count>0){
//				intersectionList.add(zcglCwInvoicingIdList);
//            }
//            AllIdList.addAll(zcglCwInvoicingIdList);
//            }
//            total+=zcglCwInvoicingNum;
//		List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
//		if (total>0){
//		if (intersection.size()==0){
//		    intersection.add("jnpfNullList");
//		}
//         zcglCwInvoiceQueryWrapper.lambda().in(ZcglCwInvoiceEntity::getId, intersection);
//		}
//        //是否有高级查询
//		if (StringUtil.isNotEmpty(superOp)){
//		    if (allSuperIDlist.size()==0){
//		        allSuperIDlist.add("jnpfNullList");
//		    }
//		List<String> finalAllSuperIDlist = allSuperIDlist;
//            zcglCwInvoiceQueryWrapper.lambda().and(t->t.in(ZcglCwInvoiceEntity::getId, finalAllSuperIDlist));
//		}
//
//        //排序
//        if(StringUtil.isEmpty(zcglCwInvoicePagination.getSidx())){
//        zcglCwInvoiceQueryWrapper.lambda().orderByDesc(ZcglCwInvoiceEntity::getId);
//        }else{
//            try {
//            	String sidx = zcglCwInvoicePagination.getSidx();
//                ZcglCwInvoiceEntity zcglCwInvoiceEntity = new ZcglCwInvoiceEntity();
//				Field declaredField = zcglCwInvoiceEntity.getClass().getDeclaredField(sidx);
//				declaredField.setAccessible(true);
//				String value = declaredField.getAnnotation(TableField.class).value();
//                 zcglCwInvoiceQueryWrapper="asc".equals(zcglCwInvoicePagination.getSort().toLowerCase())?zcglCwInvoiceQueryWrapper.orderByAsc(value):zcglCwInvoiceQueryWrapper.orderByDesc(value);
//            } catch (NoSuchFieldException e) {
//                e.printStackTrace();
//            }
//        }
//        if("0".equals(dataType)){
//            if((total>0 && AllIdList.size()>0) || total==0){
//                Page<ZcglCwInvoiceEntity> page=new Page<>(zcglCwInvoicePagination.getCurrentPage(), zcglCwInvoicePagination.getPageSize());
//                IPage<ZcglCwInvoiceEntity> userIPage=this.page(page, zcglCwInvoiceQueryWrapper);
//                return zcglCwInvoicePagination.setData(userIPage.getRecords(),userIPage.getTotal());
//            }else{
//                List<ZcglCwInvoiceEntity> list = new ArrayList();
//                return zcglCwInvoicePagination.setData(list, list.size());
//            }
//        }else{
//            return this.list(zcglCwInvoiceQueryWrapper);
//        }
        return null;
    }


    @Override
    public ZcglCwInvoiceEntity getInfo(String id){
        QueryWrapper<ZcglCwInvoiceEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcglCwInvoiceEntity::getId,id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcglCwInvoiceEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcglCwInvoiceEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ZcglCwInvoiceEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法



    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcglCwInvoiceForm form, int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		if (isUp){
			 id = form.getId();
		}
        if (total>0){
        return true;
        }
        return false ;
    }

    @Override
    public IPage<ZcglCwInvoiceListVO> getListPage(ZcglCwInvoicePagination pagination) {
        return this.baseMapper.getListPage(new Page<ZcglCwInvoiceListVO>(pagination.getCurrentPage(), pagination.getPageSize()),pagination);
    }

    @Override
    public ActionResult detailInfo(String id) {
        ZcglCwInvoiceEntity entity = getInfo(id);
        ZcglCwInvoiceInfoVO vo = JsonUtil.getJsonToBean(entity, ZcglCwInvoiceInfoVO.class);

        //子表数据转换
        List<ZcglCwInvoiceItemEntity> cwInvoiceItemEntities = zcglCwInvoiceItemMapper.selectList(new QueryWrapper<ZcglCwInvoiceItemEntity>()
                .eq("F_ParentId", id)
        );
        if(IterUtil.isNotEmpty(cwInvoiceItemEntities)){
            List<ZcglCwInvoiceItemVO> zcglCwInvoiceItemVOS = JsonUtil.getJsonToList(cwInvoiceItemEntities, ZcglCwInvoiceItemVO.class);
            vo.setItems(zcglCwInvoiceItemVOS);
        }

        //附表数据转换
        List<ZcglCwInvoicingEntity> entities = zcglCwInvoicingMapper.selectList(new QueryWrapper<ZcglCwInvoicingEntity>()
                .eq("F_ParentId", id)
        );
        if(IterUtil.isNotEmpty(entities)){
            List<ZcglCwInvoicingVO> invoicingVOS = JsonUtil.getJsonToList(entities, ZcglCwInvoicingVO.class);
            vo.setInvoicings(invoicingVOS);
        }

        return ActionResult.success(vo);
    }

    @Override
    public ActionResult commit(ZcglCwInvoiceForm zcglCwInvoiceForm) {
        /*
        * 发票提交逻辑
        * 1.需要调用第三方开票接口，成功即进行第二步，调用出错则抛出异常
        * 2.将子表中的数据先清空，然后插入提交的子表数据即可
        * */

        //调用第三方接口

        String mainId = RandomUtil.uuId();
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        List<ZcglCwInvoicingEntity> invoicings = zcglCwInvoiceForm.getInvoicings();
        if(IterUtil.isNotEmpty(invoicings)){
            zcglCwInvoicingMapper.delete(new QueryWrapper<ZcglCwInvoicingEntity>()
                    .eq("F_ParentId", zcglCwInvoiceForm.getId())
            );
            invoicings.stream().forEach(i->{
                i.setParentid(zcglCwInvoiceForm.getId());
                i.setCreatortime(new Date());
                i.setCreatoruserid(userEntity.getId());
                i.setId(RandomUtil.uuId());
                zcglCwInvoicingMapper.insert(i);
            });
        }


        List<ZcglCwInvoiceItemEntity> items = zcglCwInvoiceForm.getItems();
        if(IterUtil.isNotEmpty(items)){
            zcglCwInvoiceItemMapper.delete(new QueryWrapper<ZcglCwInvoiceItemEntity>()
                    .eq("F_ParentId", zcglCwInvoiceForm.getId())
            );
            items.stream().forEach(i->{
                i.setParentid(zcglCwInvoiceForm.getId());
                i.setCreatortime(new Date());
                i.setCreatoruserid(userEntity.getId());
                i.setId(RandomUtil.uuId());
                zcglCwInvoiceItemMapper.insert(i);
            });
        }

        return ActionResult.success("提交成功");
    }


}
